using DG.Tweening;
using System.Collections;
using UnityEngine;

/// <summary>
/// 阳光对象 - 重构版本，符合设计思路
/// </summary>
public class Sun : MonoBehaviour
{
    [Header("阳光配置")]
    [SerializeField] private int m_SunValue = 25;
    [SerializeField] private bool m_CanCollect = true;
    [SerializeField] private CircleCollider2D m_CollectCollider;
    
    [Header("动画配置")]
    [SerializeField] private float m_JumpMinDistance = 0.3f;
    [SerializeField] private float m_JumpMaxDistance = 2f;
    [SerializeField] private float m_MoveDuration = 1f;
    [SerializeField] private float m_CollectionScaleDuration = 0.3f;
    
    [Header("收集动画配置")]
    [SerializeField] private float m_FlyToCollectDuration = 0.8f; // 飞向收集点的持续时间
    [SerializeField] private float m_FlyHeight = 2f; // 飞行高度（相对于起始位置）
    [SerializeField] private AnimationCurve m_FlyPathCurve; // 飞行路径曲线（可在Inspector中编辑）
    [SerializeField] private bool m_UseFlyAnimation = true; // 是否使用飞行动画
    
    [Header("视觉效果")]
    [SerializeField] private GameObject m_CollectionEffect; // 收集特效
    [SerializeField] private AudioClip m_CollectionSound; // 收集音效
    
    private bool m_IsCollected = false;
    private Tween m_CurrentTween;
    
    /// <summary>
    /// 阳光价值
    /// </summary>
    public int SunValue => m_SunValue;
    
    /// <summary>
    /// 是否已被收集
    /// </summary>
    public bool IsCollected => m_IsCollected;
    
    /// <summary>
    /// 是否可以收集
    /// </summary>
    public bool CanCollect => m_CanCollect && !m_IsCollected;
    
    private void Awake()
    {
        // 确保收集器存在
        if (m_CollectCollider == null)
        {
            m_CollectCollider = GetComponent<CircleCollider2D>();
        }
        
        // 初始化飞行路径曲线（如果未在Inspector中设置）
        if (m_FlyPathCurve == null)
        {
            m_FlyPathCurve = new AnimationCurve();
            m_FlyPathCurve.AddKey(0f, 0f);
            m_FlyPathCurve.AddKey(1f, 1f);
        }
    }
    
    /// <summary>
    /// 初始化阳光
    /// </summary>
    /// <param name="value">阳光价值</param>
    public void Initialize(int value)
    {
        m_SunValue = Mathf.Max(1, value);
        m_CanCollect = true;
        m_IsCollected = false;
        
        // 重置状态
        transform.localScale = Vector3.one;
        
        //Logger.Log("Sun", $"阳光初始化 - 价值: {m_SunValue}");
    }
    
    /// <summary>
    /// 启用收集
    /// </summary>
    public void EnableCollection()
    {
        m_CanCollect = true;
        if (m_CollectCollider != null)
        {
            m_CollectCollider.enabled = true;
        }
    }
    
    /// <summary>
    /// 禁用收集
    /// </summary>
    public void DisableCollection()
    {
        m_CanCollect = false;
        if (m_CollectCollider != null)
        {
            m_CollectCollider.enabled = false;
        }
    }
    
    /// <summary>
    /// 跳跃动画
    /// </summary>
    /// <param name="origin">起始位置</param>
    public void DoJump(Transform origin)
    {
        if (m_CurrentTween != null && m_CurrentTween.IsActive())
        {
            m_CurrentTween.Kill();
        }
        
        float distance = Random.Range(m_JumpMinDistance, m_JumpMaxDistance);
        distance = Random.Range(0, 2) < 1 ? -distance : distance;
        
        Vector3 targetPos = transform.localPosition;
        targetPos.x += distance;
        targetPos.z = -1;
        
        Vector3 centerPos = (transform.localPosition + targetPos) / 2;
        float jumpDistance = Vector3.Distance(transform.localPosition, targetPos);
        centerPos.y += (jumpDistance / 2);
        
        m_CurrentTween = transform.DOLocalPath(
            new Vector3[] { transform.localPosition, centerPos, targetPos },
            m_MoveDuration, 
            PathType.CatmullRom
        ).SetEase(Ease.OutQuad);
    }
    
    /// <summary>
    /// 直线移动动画
    /// </summary>
    /// <param name="origin">起始位置</param>
    public void DoLine(Transform origin)
    {
        if (m_CurrentTween != null && m_CurrentTween.IsActive())
        {
            m_CurrentTween.Kill();
        }
        
        Vector3 position = new Vector3(Random.Range(-5, 6.5f), Random.Range(-4, 3f), -1);
        
        m_CurrentTween = transform.DOMove(position, m_MoveDuration)
            .SetEase(Ease.OutQuad);
    }
    
    /// <summary>
    /// 点击收集 - 使用事件系统解耦
    /// </summary>
    public void OnClick()
    {
        if (!CanCollect) return;
        
        StartCollection();
    }
    
    /// <summary>
    /// 开始收集过程
    /// </summary>
    public void StartCollection()
    {
        if (m_IsCollected) return;
        
        m_IsCollected = true;
        DisableCollection();
        
        // 停止当前动画
        if (m_CurrentTween != null && m_CurrentTween.IsActive())
        {
            m_CurrentTween.Kill();
        }
        
        // 播放收集特效
        PlayCollectionEffects();
        
        // 使用飞行动画或简单缩放动画
        if (m_UseFlyAnimation)
        {
            FlyToCollectPoint();
        }
        else
        {
            // 降级到简单缩放动画
            m_CurrentTween = transform.DOScale(Vector3.zero, m_CollectionScaleDuration)
                .SetEase(Ease.OutQuad)
                .OnComplete(() => OnCollectionComplete());
        }
    }
    
    /// <summary>
    /// 飞向收集点动画（类似植物大战僵尸）
    /// </summary>
    private void FlyToCollectPoint()
    {
        // 获取收集点位置
        Vector3 collectPoint = GetCollectPointWorldPosition();
        Vector3 startPos = transform.position;
        
        // 计算飞行路径（带抛物线效果）
        Vector3 midPoint = Vector3.Lerp(startPos, collectPoint, 0.5f);
        midPoint.y += m_FlyHeight; // 添加高度形成抛物线
        
        // 创建路径数组（三个点：起点、中点、终点）
        Vector3[] path = new Vector3[] { startPos, midPoint, collectPoint };
        
        // 使用DOTween的Sequence组合多个动画
        Sequence sequence = DOTween.Sequence();
        
        // 路径移动动画（抛物线飞行）
        sequence.Append(transform.DOPath(path, m_FlyToCollectDuration, PathType.CatmullRom)
            .SetEase(Ease.InOutQuad)
            .SetLookAt(0.01f) // 朝向移动方向
        );
        
        // 同时进行缩放动画（从正常大小到小，在飞行的70%时完成）
        float scaleDuration = m_FlyToCollectDuration * 0.7f;
        sequence.Join(transform.DOScale(Vector3.zero, scaleDuration)
            .SetEase(Ease.InQuad)
        );
        
        // 添加旋转效果（360度旋转）
        sequence.Join(transform.DORotate(new Vector3(0, 0, 360), m_FlyToCollectDuration, RotateMode.FastBeyond360)
            .SetEase(Ease.InOutQuad)
        );
        
        // 完成后回调
        sequence.OnComplete(() => OnCollectionComplete());
        
        // 确保动画可以正常停止
        sequence.SetAutoKill(true);
        
        m_CurrentTween = sequence;
    }
    
    /// <summary>
    /// 获取收集点的世界坐标位置
    /// </summary>
    private Vector3 GetCollectPointWorldPosition()
    {
        // 通过固定路径查找：GameApp/Canvas/SunLabel
        GameObject gameAppObj = GameObject.Find("GameApp");
        if (gameAppObj != null)
        {
            Transform canvasTransform = gameAppObj.transform.Find("Canvas");
            if (canvasTransform != null)
            {
                Transform sunLabelTransform = canvasTransform.Find("SunLabel");
                if (sunLabelTransform != null)
                {
                    GameObject sunLabelObj = sunLabelTransform.gameObject;
                    RectTransform rectTransform = sunLabelObj.GetComponent<RectTransform>();
                    
                    if (rectTransform != null)
                    {
                        Canvas canvas = rectTransform.GetComponentInParent<Canvas>();
                        Camera mainCamera = Camera.main;
                        
                        if (canvas != null && mainCamera != null)
                        {
                            // 获取UI元素的世界坐标位置
                            Vector3[] worldCorners = new Vector3[4];
                            rectTransform.GetWorldCorners(worldCorners);
                            
                            // worldCorners顺序：左下(0), 左上(1), 右上(2), 右下(3)
                            Vector3 collectPoint = worldCorners[1]; // 左上角
                            
                            // 对于Screen Space - Overlay模式，需要转换屏幕坐标到世界坐标
                            if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
                            {
                                // 使用合适的Z距离（确保在相机前方）
                                float zDistance = 10f; // 根据场景调整
                                Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(null, collectPoint);
                                collectPoint = mainCamera.ScreenToWorldPoint(new Vector3(screenPos.x, screenPos.y, zDistance));
                            }
                            // 对于Screen Space - Camera模式和World Space模式，worldCorners返回的是世界坐标，直接使用
                            
                            return collectPoint;
                        }
                    }
                }
            }
        }
        
        // 降级方案1：尝试通过GameUI获取
        //GameUI gameUI = FindObjectOfType<GameUI>();
        //if (gameUI != null && gameUI.Txt_SunPower != null)
        //{
        //    RectTransform rectTransform = gameUI.Txt_SunPower.rectTransform;
        //    Canvas canvas = rectTransform.GetComponentInParent<Canvas>();
        //    Camera mainCamera = Camera.main;
            
        //    if (canvas != null && mainCamera != null)
        //    {
        //        Vector3[] worldCorners = new Vector3[4];
        //        rectTransform.GetWorldCorners(worldCorners);
        //        Vector3 collectPoint = worldCorners[1];
                
        //        if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
        //        {
        //            float zDistance = 10f;
        //            Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(null, collectPoint);
        //            collectPoint = mainCamera.ScreenToWorldPoint(new Vector3(screenPos.x, screenPos.y, zDistance));
        //        }
                
        //        return collectPoint;
        //    }
        //}
        
        // 降级方案2：使用默认位置（屏幕左上角）
        Camera fallbackCamera = Camera.main;
        if (fallbackCamera != null)
        {
            Vector3 screenPos = new Vector3(150, Screen.height - 100, 10);
            return fallbackCamera.ScreenToWorldPoint(screenPos);
        }
        
        // 最后的降级方案：返回当前位置上方
        return transform.position + Vector3.up * 5f;
    }
    
    /// <summary>
    /// 播放收集特效
    /// </summary>
    private void PlayCollectionEffects()
    {
        // 播放收集特效
        if (m_CollectionEffect != null)
        {
            Instantiate(m_CollectionEffect, transform.position, Quaternion.identity);
        }
        
        // 播放收集音效
        if (m_CollectionSound != null)
        {
            AudioSource.PlayClipAtPoint(m_CollectionSound, transform.position);
        }
    }
    
    /// <summary>
    /// 收集完成处理 - 使用事件系统解耦
    /// </summary>
    private void OnCollectionComplete()
    {
        // 通过事件系统通知收集阳光
        var collectedArgs = ReferencePool.Acquire<SunCollectedEventArgs>();
        collectedArgs.Sun = this;
        collectedArgs.SunValue = m_SunValue;
        EventHelper.Fire(this, collectedArgs);
        
        // 通过事件系统通知阳光生产
        var producedArgs = ReferencePool.Acquire<SunProducedEventArgs>();
        producedArgs.Sun = this;
        producedArgs.Position = transform.position;
        EventHelper.Fire(this, producedArgs);
        
        Logger.Log("Sun", $"阳光收集完成 - 价值: {m_SunValue}");
        
        // 归还到对象池
        ReturnToPool();
    }
    
    /// <summary>
    /// 归还到对象池
    /// </summary>
    private void ReturnToPool()
    {
        // 使用事件系统通知对象池
        var returnArgs = ReferencePool.Acquire<SunReturnToPoolEventArgs>();
        returnArgs.Sun = this;
        EventHelper.Fire(this, returnArgs);
        
        // 降级到直接调用（保持向后兼容）
        if (SunPool.Instance != null)
        {
            SunPool.Instance.ReturnSun(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    /// <summary>
    /// 设置阳光价值
    /// </summary>
    public void SetValue(int value)
    {
        m_SunValue = Mathf.Max(1, value);
    }
    
    /// <summary>
    /// 设置动画参数
    /// </summary>
    public void SetAnimationParams(float jumpMin, float jumpMax, float duration)
    {
        m_JumpMinDistance = Mathf.Max(0.1f, jumpMin);
        m_JumpMaxDistance = Mathf.Max(m_JumpMinDistance, jumpMax);
        m_MoveDuration = Mathf.Max(0.1f, duration);
    }
    
    /// <summary>
    /// 强制收集（用于测试或特殊技能）
    /// </summary>
    public void ForceCollect()
    {
        if (!m_IsCollected)
        {
            StartCollection();
        }
    }
    
    /// <summary>
    /// 重置阳光状态
    /// </summary>
    public void Reset()
    {
        m_IsCollected = false;
        m_CanCollect = true;
        transform.localScale = Vector3.one;
        
        if (m_CurrentTween != null && m_CurrentTween.IsActive())
        {
            m_CurrentTween.Kill();
        }
        
        EnableCollection();
    }
    
    private void OnDestroy()
    {
        // 清理动画
        if (m_CurrentTween != null && m_CurrentTween.IsActive())
        {
            m_CurrentTween.Kill();
        }
    }
    
    private void OnDisable()
    {
        // 清理动画
        if (m_CurrentTween != null && m_CurrentTween.IsActive())
        {
            m_CurrentTween.Kill();
        }
    }
    
    #if UNITY_EDITOR
    /// <summary>
    /// 在编辑器中显示收集范围
    /// </summary>
    private void OnDrawGizmosSelected()
    {
        if (m_CollectCollider != null)
        {
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere(transform.position, m_CollectCollider.radius);
        }
    }
    #endif
}